package com.xingchen.feima.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingchen.feima.system.entity.Role;
import com.xingchen.feima.common.entity.User;
import com.xingchen.feima.system.entity.UserRole;
import com.xingchen.feima.system.entity.vo.RouteVo;
import com.xingchen.feima.system.mapper.UserMapper;
import com.xingchen.feima.system.service.MenuService;
import com.xingchen.feima.system.service.RoleService;
import com.xingchen.feima.system.service.UserRoleService;
import com.xingchen.feima.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yangxc
 * @since 2024-07-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public Map<String, Object> getUserInfo(String username) {
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        // 根据用户id获取路由列表
        List<RouteVo> routeVoList = menuService.getRouteVoList(user.getId());
        // 根据用户id获取按钮列表
        List<String> buttonList = menuService.findUserPermsList(user.getId());
        // 根据用户id获取已分配的角色列表
        List<UserRole> userRoleList = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
        List<Long> roleIdList = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Role> roleList = (List<Role>) roleService.listByIds(roleIdList);

        Map<String, Object> result = new HashMap<>();
        result.put("personalInfo", user);
        result.put("roles",  roleList);
        result.put("buttons", buttonList);
        result.put("routers", routeVoList);
        return result;
    }

    @Override
    public User getSysUserByUsername(String username) {

        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }
}
